import { useState } from "react";
import { useAppDispatch } from "../hooks/redux";
import { toggleTodo, editTodo } from "../store/todoSlice";
import { Todo } from "../types";

interface TodoListProps {
  todos: Todo[];
}

export function TodoList({ todos }: TodoListProps) {
  const dispatch = useAppDispatch();
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editText, setEditText] = useState("");

  const startEditing = (todo: Todo) => {
    setEditingId(todo.id);
    setEditText(todo.text);
  };

  const handleEdit = (id: string) => {
    if (editText.trim()) {
      dispatch(editTodo({ id, text: editText.trim() }));
      setEditingId(null);
    }
  };

  return (
    <ul className="space-y-2">
      {todos.map((todo) => (
        <li
          key={todo.id}
          className="flex items-center gap-2 p-2 border rounded-lg hover:bg-gray-50"
        >
          <input
            type="checkbox"
            checked={todo.isDone}
            onChange={() => dispatch(toggleTodo(todo.id))}
            className="w-5 h-5"
          />

          {editingId === todo.id ? (
            <input
              type="text"
              value={editText}
              onChange={(e) => setEditText(e.target.value)}
              onBlur={() => handleEdit(todo.id)}
              onKeyDown={(e) => e.key === "Enter" && handleEdit(todo.id)}
              className="flex-1 px-2 py-1 border rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
              autoFocus
            />
          ) : (
            <span
              onDoubleClick={() => startEditing(todo)}
              className={`flex-1 ${todo.isDone ? "line-through text-gray-500" : ""}`}
            >
              {todo.text}
            </span>
          )}
        </li>
      ))}
    </ul>
  );
}
